<?php

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#
#	FILE:			includes/custom/adminhandler.php
#	FUNCTION:		Handles the Page, User, and Group admin pages
#	AUTHOR:			Cameron Morrow
#	CREATED:		27/07/2005
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# F O R M A T T I N G
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

# Get table property information for this data

if ($PAGE_MODE == "add" || $PAGE_MODE == "edit") {
	$data_formatting = getRecord("SELECT * FROM " . $PROJECT_DB_TABLES["table_properties"] . " WHERE tp_table = '" . $current_table . "' ORDER BY tp_formorder ASC");
} else {
	$data_formatting = getRecord("SELECT * FROM " . $PROJECT_DB_TABLES["table_properties"] . " WHERE tp_table = '" . $current_table . "' ORDER BY tp_browsesortorder ASC");
}

# Create TableProperties
$data_properties = new TableProperties();

# Add properties
foreach ($data_formatting as $row_format) {

	# If removing some, check them now
	if (@!is_array($remove_columns) || findInArray($remove_columns, $row_format["tp_field"]) === false || ($PAGE_MODE != "" && $PAGE_MODE != "delete")) {
		$data_properties -> addProperty(new TableProperty($row_format["tp_field"], $row_format));
	}
}

# Add custom columns
foreach ($custom_columns as $custom_column) {
	$data_properties -> addCustomColumn($custom_column[0], $custom_column[1]);
}

# Convert name to suitable CSS class
$name_class = preg_replace(
	array("/\ /i"),
	array(""),
	strtolower($type_name));

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# M O D E S
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
switch ($PAGE_MODE) {

	# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	# B R O W S E   ( O R   D E L E T E )
	# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	case "delete":

		# Error message
		$error_message = "<p>Sorry, an error occured and the item could not be deleted.</p>";

		# Can proceed OK
		$can_proceed = true;

		# If properties page, remove the column first
		if ($PAGE_ID == "adminproperties") {

			# Get field and table name
			$property_details = getRecord("SELECT tp_table, tp_field FROM " . $PROJECT_DB_TABLES["table_properties"] . " WHERE tp_id = " . $PASSED_ID);

			# If got details OK
			if ($property_details !== false && count($property_details) == 1) {

				# Delete field
				$sql = "ALTER TABLE " . $property_details[0]["tp_table"] . " DROP COLUMN " . $property_details[0]["tp_field"];

				# Try deleting
				if (!executeSQLQuery($sql)) {

					# Message
					addMessage($error_message, 2);

					addError("<p>A property was to be deleted, but the SQL ALTER command could not be executed.</p><pre>" . $sql . "</pre>", 1);

					# Fail
					$can_proceed = false;
				}

			} else {

				addError("<p>A property was to be deleted, but details about it could not be retrieved.</p>", 1);

				# Message
				addMessage($error_message, 2);

				# Fail
				$can_proceed = false;
			}
		}

		# If it can proceed
		if ($can_proceed) {

			# Construct SQL
			$sql = "DELETE FROM " . $current_table . " WHERE " . $index_field . " = " . (!$index_numeric ? "\"" : "") . $PASSED_ID . (!$index_numeric ? "\"" : "");
			
			# Try executing
			if (executeSQLQuery($sql)) {
				
				if($PAGE_ID == "adminusers"){
					
					$deleteSql1 = "DELETE FROM ".$PROJECT_DB_TABLES["usergroup"]." WHERE ug_u_id = '".$PASSED_ID."'";
									
					executeSQLQuery($deleteSql1);
					
					#clear user group data
					$deleteSql2 = "DELETE FROM ".$PROJECT_DB_TABLES["users_newsletter_group"]." WHERE ung_u_id = '".$PASSED_ID."'";
									
					executeSQLQuery($deleteSql2);
				}
				else if($PAGE_ID == "admingroups"){
					
					$deleteSql1 = "DELETE FROM ".$PROJECT_DB_TABLES["editgroup"]." WHERE eg_g_id = '".$PASSED_ID."' OR eg_eg_id = '".$PASSED_ID."'";
									
					executeSQLQuery($deleteSql1);
					
					#clear user group data
					$deleteSql2 = "DELETE FROM ".$PROJECT_DB_TABLES["usergroup"]." WHERE ug_g_id = '".$PASSED_ID."'";
									
					executeSQLQuery($deleteSql2);
				}

				# Log
				logDeletedItem($current_table, $PASSED_ID);

				addMessage("<p>OK, item was deleted successfully.</p>");
			} else {

				addMessage($error_message, 2);
				
				addError("<p>An error occured and the SQL DELETE command could not be executed.</p><pre>" . $sql . "</pre>", 1);
			}
		}
		
	case "restore":
	
		if($PAGE_MODE=="restore"){
			
			$sql_p_parent="SELECT * FROM ".$current_table." WHERE p_id=\"".$PASSED_ID."\"";
		
			$current_data_p_parent=getRecord($sql_p_parent);
			
			$sql_p_id="SELECT * FROM ".$current_table." WHERE p_parent=\"".$current_data_p_parent[0]["p_parent"]."\" AND p_status<3 AND p_status>0";
			$current_data_p_id=getRecord($sql_p_id);
			
			$restored_sort=count($current_data_p_id)+2;
				
				
			$sql = "UPDATE " . $current_table ." SET p_status=0, p_sort=".$restored_sort. " WHERE " . $index_field . " = " . (!$index_numeric ? "\"" : "") . $PASSED_ID . (!$index_numeric ? "\"" : "");
				# Try executing
			if (executeSQLQuery($sql)) {
	
					# Log
				logDeletedItem($current_table, $PASSED_ID);
				
				addMessage("<p>OK, item was restored successfully.</p>");
			} else {
	
				addMessage($error_message, 2);
					
				addError("<p>An error occured and the SQL restore command could not be executed.</p><pre>" . $sql . "</pre>", 1);
			}
		}
		
	# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	# Remove
	# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	case "remove":
		if($PAGE_MODE=="remove"){
			$sql = "UPDATE " . $current_table ." SET p_status=3". " WHERE " . $index_field . " = " . (!$index_numeric ? "\"" : "") . $PASSED_ID . (!$index_numeric ? "\"" : "");
				# Try executing
			if (executeSQLQuery($sql)) {
	
					# Log
				logDeletedItem($current_table, $PASSED_ID);
				
				#change the sort for the pages
				$sql_p_parent="SELECT * FROM ".$current_table." WHERE p_id=\"".$PASSED_ID."\"";

				$current_data_p_parent=getRecord($sql_p_parent);
				
				$sql_p_id="SELECT * FROM ".$current_table." WHERE p_parent=\"".$current_data_p_parent[0]["p_parent"]."\" AND p_status<3 AND p_status>0";
				$current_data_p_id=getRecord($sql_p_id);
				
				foreach($current_data_p_id as $current_data_p_id_key=>$current_data_p_id_value){
					$sql_update_sort='';
					if($current_data_p_id_value['p_sort']>$current_data_p_parent[0]['p_sort']){
						$replaced_sort=$current_data_p_id_value['p_sort']-1;
						$sql_update_sort="UPDATE ".$current_table." SET p_sort=".$replaced_sort." WHERE p_id=\"".$current_data_p_id_value['p_id']."\"";
					}
					executeSQLQuery($sql_update_sort);
				}
				
				
	
				addMessage("<p>OK, item was removed successfully.</p>");
			} else {
	
				addMessage($error_message, 2);
					
				addError("<p>An error occured and the SQL remove command could not be executed.</p><pre>" . $sql . "</pre>", 1);
			}
		}
	case "":
	
		$flagExcute = true;
	
		if($PAGE_ID == "adminusers"){
			
			$browse_sql = "SELECT u.u_id as u_id,u.u_created as u_created,u_modified as u_modified,u.u_email as u_email,g.g_name as g_name,u.u_created as u_created,u.u_lastlogin as u_lastlogin, u.u_login_name as u_login_name ";
			
			$browse_sql .= "FROM ".$PROJECT_DB_TABLES["usergroup"]." ug ";
			
			$browse_sql .= "INNER JOIN ".$PROJECT_DB_TABLES["groups"]." g on ug.ug_g_id = g.g_id ";
			
			$browse_sql .= "INNER JOIN ".$PROJECT_DB_TABLES["editgroup"]." eg on g.g_id = eg.eg_eg_id ";
			
			$browse_sql .= "RIGHT JOIN ".$PROJECT_DB_TABLES["users"]." u on u.u_id = ug.ug_u_id ";
			
			$arrUserGroups = $USER -> getGroup()->getGroupArray();
			
			if(count($arrUserGroups)>0){
				
				$browse_sql .= "WHERE ";
			}
			
			$index = 0;
			
			foreach($arrUserGroups as $objUserGroup){
				
				if($index == 0){
				
					$browse_sql .= "eg.eg_g_id = '".$objUserGroup -> getID()."' ";
				}
				else{
					
					$browse_sql .= " OR eg.eg_g_id = '".$objUserGroup -> getID()."' ";
				}
				
				$index ++;
			}
			
			$browse_sql .= " OR ug.ug_g_id IS NULL ";
			
			$browse_sql .= " ORDER BY u.u_id ";

		}
		else if($PAGE_ID == "admingroups"){
			
			$browse_sql = "SELECT DISTINCT g2.g_id as g_id, g2.g_name as g_name,g2.g_created as g_created,g2.g_modified as g_modified ";
			
			$browse_sql .= "FROM ".$PROJECT_DB_TABLES["users"]." u ";
			
			$browse_sql .= "INNER JOIN ".$PROJECT_DB_TABLES["usergroup"]." ug ON u.u_id = ug.ug_u_id ";
			
			$browse_sql .= "INNER JOIN ".$PROJECT_DB_TABLES["groups"]." g1 ON ug.ug_g_id = g1.g_id ";
			
			$browse_sql .= "INNER JOIN ".$PROJECT_DB_TABLES["editgroup"]." eg ON g1.g_id = eg.eg_g_id ";
			
			$browse_sql .= "INNER JOIN ".$PROJECT_DB_TABLES["groups"]." g2 ON eg.eg_eg_id = g2.g_id ";
			
			$browse_sql .= "ORDER BY g2.g_name";
			
			//echo $browse_sql."<br/>";
		}
		else if($PAGE_ID == "adminpages"){
			
			$browse_sql = "";
			
			$flagExcute = false;
			
		}
		else{

			# Create Browse SQL
			$browse_sql = "SELECT " . $current_table . ".*";
			if (count($edit_sql_additional_selects) > 0) {
				$browse_sql .= ", " . implode(", ", $edit_sql_additional_selects);
			}
			$browse_sql .= " FROM " . $current_table;
			if (count($edit_sql_additional_tables) > 0) {
				$browse_sql .= ", " . implode(", ", $edit_sql_additional_tables); 
			}
	
			if (count($browse_sql_additional_where_clauses) > 0) {
				$browse_sql .= " WHERE ";
				foreach ($browse_sql_additional_where_clauses as $clause_count => $where_clause) {
					$browse_sql .= $where_clause;
					if ($clause_count < count($browse_sql_additional_where_clauses) - 1) {
						$browse_sql .= " AND ";
					}
				}
			}
		
			# Search term
			if ($SEARCH_TERM != "") {
	
				# Add a AND or a WHERE
				if (count($browse_sql_additional_where_clauses) > 0) {
					$browse_sql .= " AND (";
				} else {
					$browse_sql .= " WHERE (";
				}
				
				# Search each of the fields that can be searched
				foreach ($browse_sql_search_fields as $counter => $search_field) {
	
					# For each of the search terms
					foreach (explode(" ", $SEARCH_TERM) as $term_counter => $term) {
						$browse_sql .= $search_field . " LIKE \"%" . $term . "%\"";
						if ($term_counter < count(explode(" ", $SEARCH_TERM)) - 1) {
							$browse_sql .= " OR ";
						}
					}
	
					#$browse_sql .= $search_field . " LIKE \"%" . $SEARCH_TERM . "%\"";
					if ($counter < count($browse_sql_search_fields) - 1) {
						$browse_sql .= " OR ";
					}
				}
				$browse_sql .= ")";
			}
			
	
			# Check other limits
			if (@$include_logged_in_status_limits) {
	
				# Get values
				$limit_logged_in = (@$_POST["loggedin"] || (@$_POST["loggedin"] == false && @$_POST["notloggedin"] == false)) ? true : false;
				$limit_not_logged_in = (@$_POST["notloggedin"] || (@$_POST["loggedin"] == false && @$_POST["notloggedin"] == false)) ? true : false;
	
				if (($limit_logged_in && !$limit_not_logged_in) || (!$limit_logged_in && $limit_not_logged_in)) {
	
					if (strpos($browse_sql, " WHERE ") === false) {
						$browse_sql .= " WHERE (";
					} else {
						$browse_sql .= " AND (";
					}
	
					if ($limit_logged_in) {
						$browse_sql .= "u_isloggedin = 1";
					} else {
						$browse_sql .= "u_isloggedin = 0";
					}
	
					$browse_sql .= ")";
				}
			}
	
			$browse_sql .= " ORDER BY ";
			if ($browse_group_field != "") {
				if (@$browse_group_sort_type) {
					$browse_sql .= $browse_group_field . " " . $browse_group_sort_type . ", ";
				} else {
					$browse_sql .= $browse_group_field . " ASC, ";
				}
			}
			$browse_sql .= $browse_sort_field . " ASC";
		}

		if($flagExcute){
			
			# Get current data
			$current_data = getRecord($browse_sql, $index_field);
		}

		$html_dropdownlist = "";
				
		# Search form
		addContent("<h2 class=\"search\">Search:</h2><form name=\"searchitemform\" id=\"searchitemform\" action=\"" . $PAGE_ID . ".php\" method=\"post\">" .
			"<input type=\"hidden\" name=\"result\" id=\"result\" value=\"1\"/>" .
			"<p>Search " . $type_name_plural . ":<input type=\"text\" size=\"50\" name=\"search\" id=\"search\" value=\"" . $SEARCH_TERM . "\" onkeyup=\"showSearchResult(this.value,'".$PAGE_ID."')\"/> <input type=\"submit\" value=\"Search\" />".$html_dropdownlist."</p>");
			
		addContent((@$include_logged_in_status_limits ? "<p>Limit to: <input type=\"checkbox\" id=\"loggedin\" name=\"loggedin\"" . ($limit_logged_in ? " checked=\"checked\"" : "") . " /> <label for=\"loggedin\">Logged in users</label> " .
				"<input type=\"checkbox\" id=\"notloggedin\" name=\"notloggedin\"" . ($limit_not_logged_in ? " checked=\"checked\"" : "") . " /> <label for=\"notloggedin\">Not logged in users</label> " .
				"</p>" : "") ."</form>");//<input type=\"submit\" value=\"reorganize\" name=\"reorganize\" />

		# Add link
		addContent("<h2 class=\"" . $name_class . "add\">Add a " . $type_name . "</h2>");
		
		# Form
		addContent(generateAddLink($type_name));

		# Draw the table
		if (($PAGE_ID != "adminpages" && $PAGE_ID != "adminusers" && $PAGE_ID != "xml_editor")|| $SEARCH_TERM != "" ) {
			addContent($data_properties -> drawBrowseTable($current_data, (($SEARCH_TERM == "") ? "Browsing " : "Search results in ") . $type_name_plural, $browse_group_field, $name_class));

		} 
		#Admin ussers when the search term is empty string
		else if($PAGE_ID == "adminusers" && $SEARCH_TERM==""){
			
			$objHtmlAdminUser = new htmlAdminUser();
			
			$objHtmlAdminUser -> adminUserPrintOutFrame($current_data);
		}
		else if($PAGE_ID == "adminpages" && $SEARCH_TERM==""){
			
			//#sql script for the pages without parent
//			$browse_sql_no_parent="select * from ".$PROJECT_DB_TABLES["pages"]." where p_parent=\"\" AND p_status<3";
//			
//			#get the record
//			$current_data_no_parent=getRecord($browse_sql_no_parent);
			
			#Page table
			addContent("<div id=\"txtHint\">");

			//$ROW_COUNT = 0;
//			
//			global $USER;
			
			addContent(PageView::genertatePageForm());

			addContent("</div>");

			#addContentPre(print_r($current_data, true));
		}

		# Draw the action form
		addContent(generateActionForm());

		# Add link
		addContent("<h2 class=\"" . $name_class . "add\">Add a " . $type_name . "</h2>");

		# Form
		addContent(generateAddLink($type_name));

		# Break
		break;
		
	# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	# A D D
	# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	case "add":

		# Check for submission
		if (@$_POST["submitted"]) {

			# Get data
			$data_properties -> attemptToSave("add", $index_field);
		}

		# Back to browse
		addContent("<h2>Browse for other " . $type_name_plural . "</h2>\n<p>You can see a list of other <a href=\"" . $PAGE_ID . ".php\">" . $type_name_plural . "</a>.</p>\n");

		# Header
		addContent("<h2>Adding a " . $type_name . "</h2>");
		

		//echo $data_properties -> generateInputForm("add");
		# Draw form
		addContent($data_properties -> generateInputForm("add"));

		# Break
		break;

	# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	# A D D   ( N E W S L E T T E R S ,   A U T O M A T E D
	# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	case "addnewsletter":

		addContent("<h2>Auto-adding newsletter</h2>");

		# Get Name
		$newsletter_name = (@$_POST["id"]) ? $_POST["id"] : "Untitled Newsletter (" . formatDate(getFullDate(), "d M Y g:i:sa") . ")";

		# SQL
		$sql = "INSERT INTO " . $current_table . " (";

		# Get properties
		$newsletter_properties = $data_properties -> getProperties();

		# For each
		$field_names = array();
		$field_values = array();
		foreach ($newsletter_properties as $property) {
			if ($property -> getData("tp_inserted") == "1") {

				# Add field
				$field_names[] = $property -> getData("tp_field");

				# Get value
				switch ($property -> getData("tp_field")) {

					case "p_name":
						$field_value = "\"" . $newsletter_name . "\"";
						break;

					case "p_id":
						$field_value = "\"newsletter" . getFullDate() . "\"";
						break;

					case "p_created":
					case "p_accessdatestart":
					case "p_accessdateend":
						$field_value = "\"" . getFullDate() . "\"";
						break;

					case "p_section":
						$field_value = "\"" . $NEWSLETTER_DIR_NAME . "\"";
						break;

					case "p_accesstype":
						$field_value = "1";
						break;

					case "p_access":
						$field_value = "\"-1\"";
						break;

					default:
						if ($property -> getData("tp_type") == "3" || $property -> getData("tp_type") == "4") {
							$field_value = "\"\"";
						} else {
							$field_value = "0";
						}
						
						break;
				}

				# Store value
				$field_values[] = $field_value;
			}
		}

		# Add fields
		foreach ($field_names as $counter => $field_name) {
			$sql .= $field_name . (($counter == count($field_names) - 1) ? "" : ", ");
		}

		# SQL
		$sql .= ") VALUES (";

		# Add conent
		foreach ($field_values as $counter => $field_value) {
			$sql .= $field_value . (($counter == count($field_values) - 1) ? "" : ", ");
		}
		
		# End SQL
		$sql .= ")";

		# Execute SQL
		if (executeSQLQuery($sql)) {
			header("location: " . $PAGE_ID . ".php");
		} else {

			addError("Sorry, an error occured and a new newsletter could not be added. Please contact the site developers for assistance.", 2);
		}

		break;

	# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	# E D I T
	# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	case "edit":

		# Check for submission
		if (@$_POST["submitted"]) {

			# Get data
			$data_properties -> attemptToSave("edit", $index_field, $index_numeric, $PASSED_ID);
		}
		
		$edit_sql = "";
		
		if($PAGE_ID == "adminusers"){
			
			 $edit_sql .= "SELECT u.u_id as u_id,u.u_fname as u_fname,u.u_lname as u_lname,u.u_email as u_email,u.u_login_name as u_login_name,g.g_id as g_id,g.g_name as g_name, ng.ng_id as ng_id ,ng.ng_name as ng_name ";
			 
			 $edit_sql .= "FROM isis_users u ";
			 
			 $edit_sql .= "LEFT JOIN ".$PROJECT_DB_TABLES["usergroup"]." ug ON u.u_id = ug.ug_u_id ";
			 
			 $edit_sql .= "LEFT JOIN ".$PROJECT_DB_TABLES["groups"]." g ON ug.ug_g_id = g.g_id ";	
			 
			 $edit_sql .= "LEFT JOIN ".$PROJECT_DB_TABLES["users_newsletter_group"]." ung ON ung.ung_u_id = u.u_id ";
			 
			 $edit_sql .= "LEFT JOIN ".$PROJECT_DB_TABLES["newsletter_groups"]." ng ON ung.ung_ng_id = ng.ng_id ";
			 
			 $edit_sql .= "WHERE u.u_id =  '".$PASSED_ID."'";
		}
		else if($PAGE_ID == "admingroups"){
			
			$edit_sql .= "SELECT g1.g_id AS g_id, g1.g_name AS g_name, g1.g_created AS g_created, g1.g_modified AS g_modified, g1.g_priviledges AS g_priviledges, g1.g_homepage AS g_homepage, g1.g_can_lock AS g_can_lock, g1.g_can_approve AS g_can_approve, eg.eg_g_id AS eg_eg_id,g2.g_name AS eg_eg_name ";
			
			$edit_sql .= "FROM ".$PROJECT_DB_TABLES["groups"]." g1 ";
			
			$edit_sql .= "LEFT JOIN ".$PROJECT_DB_TABLES["editgroup"]." eg ON eg.eg_eg_id = g1.g_id ";
			
			$edit_sql .= "LEFT JOIN ".$PROJECT_DB_TABLES["groups"]." g2 ON eg.eg_g_id = g2.g_id ";
			
			$edit_sql .= "WHERE g1.g_id =  '".$PASSED_ID."'";
		}
		else{

			# Construct SQL
			$edit_sql = "SELECT " . $current_table . ".*";
			
			if (count($edit_sql_additional_selects) > 0) {
				
				$edit_sql .= ", " . implode(", ", $edit_sql_additional_selects);
			}
			
			$edit_sql .= " FROM " . $current_table;
			
			if (count($edit_sql_additional_tables) > 0) {
				
				$edit_sql .= ", " . implode(", ", $edit_sql_additional_tables); 
			}
			
			$edit_sql .= " WHERE " . $index_field . " = " . ($index_numeric ? "" : "\"") . $PASSED_ID . ($index_numeric ? "" : "\"");
			
			foreach ($edit_sql_additional_where_clauses as $where_clause) {
				
				$edit_sql .= " AND " . $where_clause;
			}
		}
		
		echo $edit_sql;
		
		# Get data
		$current_data = getRecord($edit_sql);

		# Back to browse
		addContent("<h2>Browse for other " . $type_name_plural . "</h2>\n<p>You can see a list of other <a href=\"" . $PAGE_ID . ".php\">" . $type_name_plural . "</a>.</p>\n");

		# Header
		addContent("<h2>Editing a " . $type_name . "</h2>");

		if (count($current_data) > 0) {
			
			if($PAGE_ID == "adminusers" || $PAGE_ID == "admingroups"){
				
				# Draw form
				addContent($data_properties -> generateInputForm("edit", $current_data, $PASSED_ID));
			}
			else{

				# Draw form
				addContent($data_properties -> generateInputForm("edit", $current_data[0], $PASSED_ID));
			}

		} else {

			# Fail
			addContent("<p>Sorry, an error occured and the " . $type_name . " could not be loaded.</p>");
		}

		# Break
		break;
}

?>